package com.management.demo.common;

import cn.dev33.satoken.util.SaResult;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 统一异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public SaResult handlerException(MethodArgumentNotValidException exception) {
        exception.printStackTrace();
        HashMap<String, String> error = new HashMap<>();
        BindingResult bindingResult = exception.getBindingResult();
        bindingResult.getFieldErrors().forEach(item -> {
            String field = item.getField();
            String message = item.getDefaultMessage();
            error.put(field, message);
        });
        return SaResult.error("数据校验未通过").setData(error);
    }

    @ExceptionHandler
    public SaResult handlerException(Exception exception) {
        exception.printStackTrace();
        return SaResult.error(exception.getMessage());
    }
}
